package com.zkadmin.renderer;

import java.io.Serializable;

import org.apache.commons.lang3.StringUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.DefaultTreeNode;
import org.zkoss.zul.Treecell;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.TreeitemRenderer;
import org.zkoss.zul.Treerow;

import com.zkadmin.entity.SysMenu;
import com.zkadmin.util.AdminConstants;
import com.zkadmin.util.AdminWebUtils;

public class SysMenuTreeitemRenderer extends BaseRenderer implements TreeitemRenderer<DefaultTreeNode<SysMenu>> {

	@Override
	public void render(final Treeitem treeitem, DefaultTreeNode<SysMenu> data, int index) throws Exception {
		SysMenu menu = data.getData();
		Treerow treerow = new Treerow();
		treeitem.appendChild(treerow);
		treeitem.setOpen(menu.isOpen());

		MenuTreecell menuTreecell = new MenuTreecell(menu);
		menuTreecell.addEventListener(Events.ON_DOUBLE_CLICK, new EventListener<Event>() {
			public void onEvent(Event event) throws Exception {
				treeitem.setOpen(!treeitem.isOpen());
			}
		});
		treerow.appendChild(menuTreecell);

	}

	class MenuTreecell extends Treecell implements EventListener<Event>, Serializable {
		private static final long serialVersionUID = -4996212514919576716L;
		private SysMenu menu;

		public MenuTreecell(SysMenu menu) {
			this.menu = menu;
			this.setLabel(menu.getName());
			this.setIconSclass(StringUtils.isEmpty(menu.getIcon()) ? AdminConstants.DEFAULT_ICON : menu.getIcon());
			if (StringUtils.isNotBlank(menu.getUrl())) {
				addEventListener(Events.ON_CLICK, this);
			}
		}

		public void onEvent(Event event) throws Exception {
			String url = menu.getUrl();
			if (!url.startsWith(AdminConstants.PAGE_PATH)) {
				url = AdminWebUtils.getZulPagePath(url);
			}
			AdminWebUtils.openPage(url, menu.getName(), menu.getIcon());
		}
	}
}
